package com.example.spb6;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;


import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;


public class MainActivity extends AppCompatActivity {

    private final UUID mUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//蓝牙串口服务的UUID
    // 实例化蓝牙控制器
    public BlueToothController btController = new BlueToothController();
    // 蓝牙权限列表
    public ArrayList<String> requestList = new ArrayList<>();
    // 弹窗
    private Toast mToast;
    public ArrayAdapter adapter1;
    // 定义一个列表，存蓝牙设备地址，用于显示。
    public ArrayList<String> device = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_1);

        // 获取ListView组件
        ListView listView = findViewById(R.id.listView1);
        // 实例化ArrayAdapter对象
        adapter1 = new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, device);
        // 添加到ListView组件中
        listView.setAdapter(adapter1);
        // ListView的列表点击事件

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @SuppressLint("MissingPermission")
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                CharSequence content = ((TextView) view).getText();
                // 获取蓝牙的名称和地址
                String con = content.toString();
                // 换行为切割
                String[] conArray = con.split("\n");
                // 获取蓝牙地址
                String rightStr = conArray[1].substring(5);
                BluetoothDevice device1 = btController.find_device(rightStr);
                connectDevice(device1);
            }
        });

        Button open_Bt = findViewById(R.id.openBT);
        open_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                turnOnBt();
            }
        });

        Button close_Bt = findViewById(R.id.closeBT);
        close_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getPermision();
                // 关闭蓝牙
                btController.turnOffBlueTooth();
            }
        });

        Button state_Bt = findViewById(R.id.stateBT);
        state_Bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getPermision();
                // 判断当前蓝牙状态
                boolean ret = btController.getBlueToothStatus();
                // 弹窗显示结果
                showToast("当前蓝牙状态：" + ret);
            }
        });


        Button update_list = findViewById(R.id.updateList);
        update_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getPermision();
                // 初始化列表
                device.clear();
                adapter1.notifyDataSetChanged();
                // 获取已绑定蓝牙列表
                ArrayList<BluetoothDevice> bluetoothDevices = btController.getBondedDeviceList();
                // 更新列表
                for (BluetoothDevice device1 : bluetoothDevices) {
                    if (device1.getBondState() == BluetoothDevice.BOND_BONDED) {
                        device.add("设备名：" + device1.getName() + "\n" + "设备地址：" + device1.getAddress());
                    } else {
                        device.add("设备名：" + device1.getName() + "\n" + "设备地址：" + device1.getAddress() + "\n" + "连接状态：未知");
                    }
                    adapter1.notifyDataSetChanged();
                }
            }
        });
    }

    private void connectDevice(final BluetoothDevice device) {

        final UUID MY_UUID = UUID.randomUUID();

        new Thread(new Runnable() {
            @Override
            public void run() {
//                try {
//                    try (BluetoothSocket socket = device.createRfcommSocketToServiceRecord(mUUID)) {
//                        socket.connect();
//                    }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                            showAlert("连接成功", "设备名：" + device.getName() + "\n设备地址：" + device.getAddress());
                        // 跳转到新Activity
                        Intent intent = new Intent(MainActivity.this, Medicine_MainActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("address", device.getAddress());
                        bundle.putString("name", device.getName());
                        intent.putExtras(bundle);
                        startActivity(intent);
                        finish();
                    }
                });
//                } catch (IOException e) {
//                    e.printStackTrace(); // 打印详细的错误信息
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            showAlert("连接失败", "设备名：" + device.getName() + "\n设备地址：" + device.getAddress());
//                        }
//                    });
//                }
            }
        }).start();
    }

    private void showAlert(String title, String message) {
        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton("确定", null)
                .show();
    }

    public static class BlueToothController {
        private BluetoothAdapter BtAdapter;

        public BlueToothController() {
            // 获取本地的蓝牙适配器
            BtAdapter = BluetoothAdapter.getDefaultAdapter();
        }

        // 打开蓝牙
        public void turnOnBlueTooth(Activity activity, int requestCode) {
            if (!BtAdapter.isEnabled()) {
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                activity.startActivityForResult(intent, requestCode);
            }
        }

        // 关闭蓝牙
        public void turnOffBlueTooth() {
            if (BtAdapter.isEnabled()) {
                BtAdapter.disable();
            }
        }

        // 获取蓝牙状态
        public boolean getBlueToothStatus() {
            // 断言，避免BtAdapter为null导致return出错
            assert (BtAdapter != null);
            // 蓝牙状态
            return BtAdapter.isEnabled();
        }

        // 获取设备信息
        public ArrayList<BluetoothDevice> getBondedDeviceList() {
            return new ArrayList<>(BtAdapter.getBondedDevices());
        }

        // 根据蓝牙地址找到相应的设备
        public BluetoothDevice find_device(String addr) {
            return BtAdapter.getRemoteDevice(addr);
        }
    }

    public void turnOnBt() {
        getPermision();
        // 打开蓝牙
        btController.turnOnBlueTooth(this, 1);
    }

    /**
     * 动态申请权限
     */
    public void getPermision() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            requestList.add(Manifest.permission.BLUETOOTH_SCAN);
            requestList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
            requestList.add(Manifest.permission.BLUETOOTH_CONNECT);
            requestList.add(Manifest.permission.ACCESS_FINE_LOCATION);
            requestList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            requestList.add(Manifest.permission.BLUETOOTH);
        }
        if (requestList.size() != 0) {
            ActivityCompat.requestPermissions(this, requestList.toArray(new String[0]), 1);
        }
    }


    public void showToast(String text) {
        // 若Toast控件未初始化
        if (mToast == null) {
            // 则初始化
            mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
        } else {
            // 修改显示文本
            mToast.setText(text);
        }
        // 显示
        mToast.show();



    }
}